package com.css.Thread;
//生产者消费者
//管程法
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer=new SynContainer();
        new Productor(synContainer).start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Consumer(synContainer).start();


    }
}
class Productor extends Thread{
    SynContainer synContainer;

    public Productor(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synContainer.push(new Chicken(i));
            System.out.println("生产了"+i);
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }

    }
}
class Consumer extends Thread{
    SynContainer synContainer;

    public Consumer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
           Chicken chicken= synContainer.pop();
            System.out.println("消费了"+chicken.getId());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
class Chicken{
    int id;
    public Chicken(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
class SynContainer{
    //定义了缓冲区容器大小
    Chicken[]chickens=new Chicken[10];
    int count=0;
    //生产者放入
    public synchronized void push(Chicken chicken){
        //如果容器满了就需要等待消费者消费
        if(count==chickens.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        else {
            chickens[count]=chicken;
            count++;
            this.notifyAll();
        }


    }
    //消费者消费
    public synchronized Chicken pop(){
        Chicken chicken=null;
        if(count==0){
            //消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;

        }else {
            count--;
            chicken=chickens[count];
            this.notifyAll();
            return chicken;

        }
    }
}

